//
//  UIView+Add.m
//  TsingKe
//
//  Created by 代佳宏 on 2020/9/12.
//  Copyright © 2020 DaiJIaHong. All rights reserved.
//

#import "UIView+Add.h"

@implementation UIView (Add)

+ (instancetype)initFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:self options:nil] firstObject];
}

///添加高斯模糊效果
- (void)addBlurEffect {
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = self.bounds;
    [self addSubview:effectView];
    [self sendSubviewToBack:effectView];
}

///添加阴影
- (void)addShadow {
    self.layer.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3].CGColor;
    self.layer.shadowOpacity = 0.5;
    self.layer.shadowOffset = CGSizeMake(0, 0);
    self.layer.shadowRadius = 5;
}

///水平渐变色
- (void)gradientHorizontalWithFromColor:(UIColor *)fromColor withEndColor:(UIColor *)endColor {
    [self gradientCustomWithFromColor:fromColor andStartPoint:CGPointMake(0, 0) withEndColor:endColor andEndPoint:CGPointMake(1, 0)];
}

///垂直渐变色
- (void)gradientVerticalWithFromColor:(UIColor *)fromColor withEndColor:(UIColor *)endColor {
    [self gradientCustomWithFromColor:fromColor andStartPoint:CGPointMake(0, 0) withEndColor:endColor andEndPoint:CGPointMake(0, 1)];
}

///自定义渐变色
- (void)gradientCustomWithFromColor:(UIColor *)fromColor andStartPoint:(CGPoint)startPoint withEndColor:(nonnull UIColor *)endColor andEndPoint:(CGPoint)endPoint {
    CAGradientLayer *layer = [[CAGradientLayer alloc] init];
    layer.frame = self.bounds;
    layer.colors = @[(__bridge id)fromColor.CGColor,(__bridge id)endColor.CGColor];
    layer.startPoint = startPoint;
    layer.endPoint = endPoint;
    [self.layer insertSublayer:layer atIndex:0];
}

+ (id)loadCurrentViewFromNib{
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:self options:nil];
    if (array.count == 0) {
        NSString *info = [NSString stringWithFormat:@"找不到%@.xib",NSStringFromClass(self)];
        NSLog(@"类别: %@  \n方法: %@ \n行号:%d \n调试信息: %@",self,NSStringFromSelector(_cmd),__LINE__, info);
        return nil;
    }
    return [array firstObject];
}

- (UIImage *)snapshotImageWithAfterScreenUpdates:(BOOL)afterUpdates {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:afterUpdates];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snap;
}

@end
